# -*- coding: utf-8 -*-
import xbmc, xbmcgui, xbmcaddon, xbmcplugin
import urllib, urllib2
import re, string, sys, os
import urllib
import unicodedata
from entities import *


def translate(text):
    return _addon.getLocalizedString(text).encode('utf-8')

_channels    = []
_mode        = None
_addon       = xbmcaddon.Addon()
_addonname   = _addon.getAddonInfo('name')
_icon        = _addon.getAddonInfo('icon')

_username = _addon.getSetting('username')
_password = _addon.getSetting('password')

def notification(text):
    line1 = text
    time = 5000  # in miliseconds
    xbmc.executebuiltin('Notification(%s, %s, %d, %s)'%(_addonname,line1, time, _icon))
    return True

#notification(translate(30101) + ' ' + translate(30102))
#notification(_username + ' ' + _password)


def translate(text):
    return _addon.getLocalizedString(text).encode('utf-8')


def playListItem(url, name):
    #_link='rtmp://tv.webport.tv/promo2/m6'
    #_link='http://video.mystreamservice.com/480p/6981163.mp4'
    #_link='http://88.157.194.246/live/ramdisk/zsic/HLS/zsic.m3u8'
    #_link = 'http://tvzune.tv/m/m3u8_m3u8.m3u8?canal=sporttv1&token=2819354534'

    _title = name
    li = xbmcgui.ListItem(label=_title, iconImage='http://tvzune.tv/m/img/'+ name.lower() +'.png', thumbnailImage='http://tvzune.tv/m/img/'+ name.lower() +'.png', path=url)
    li.setInfo(type='Video', infoLabels={ "Title": _title})
    li.setProperty('mimetype', 'video/x-msvideo')
    li.setProperty('IsPlayable', 'true')
    xbmc.Player().play(item=url, listitem=li)
    #notification("A Dar isto")
    try:
        nowPlaying(name.lower())
    except:
        pass
    #xbmcplugin.setResolvedUrl(int(sys.argv[1]),True,li)
    return True


def playVideo():
    #_link='rtmp://tv.webport.tv/promo2/m6'
    #_link='http://video.mystreamservice.com/480p/6981163.mp4'
    _link='http://88.157.194.246/live/ramdisk/zsic/HLS/zsic.m3u8'
    #_link = 'http://tvzune.tv/m/m3u8_m3u8.m3u8?canal=sporttv1&token=2819354534'

    _title = 'M6'
    li = xbmcgui.ListItem(label=_title, iconImage=_icon, thumbnailImage=_icon, path=_link)
    li.setInfo(type='Video', infoLabels={ "Title": _title })
    li.setProperty('mimetype', 'video/x-msvideo')
    li.setProperty('IsPlayable', 'true')
    #xbmc.Player(xbmc.PLAYER_CORE_DVDPLAYER).play(_link, li)
    xbmc.Player().play(item=_link, listitem=li)


    #xbmcplugin.setResolvedUrl(int(sys.argv[1]),True,li)
    return True


def channels():  # homescreen
    addDir('[COLOR blue][B]'+ 'Live channels' + '[/B][/COLOR]', 'rtp.pt/play', '', _icon, 1, False)
    addDir('[COLOR blue][B]'+ 'Live channels' + '[/B][/COLOR]', 'rtp.pt/play', '', _icon, 1, False)
    addDir('[COLOR blue][B]'+ 'Live channels' + '[/B][/COLOR]', 'rtp.pt/play', '', _icon, 1, False)
    addDir('[COLOR blue][B]'+ 'Live channels' + '[/B][/COLOR]', 'rtp.pt/play', '', _icon, 1, False)
    addDir('[COLOR blue][B]'+ 'Live channels' + '[/B][/COLOR]', 'rtp.pt/play', '', _icon, 1, False)
    xbmc.executebuiltin("Container.SetViewMode(500)")


def addLink(name,url,iconimage,number_of_items):
    ok=True
    liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
    #liz.setProperty('fanart_image', os.path.join(artfolder,'fanart.png'))
    liz.setInfo( type="Video", infoLabels={ "Title": name } )
    ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz,isFolder=False,totalItems=number_of_items)
    return ok


def addDir(name,url,mode,iconimage,number_of_items,pasta=True):
    u = sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
    ok = True
    liz = xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
    #liz.setProperty('fanart_image', os.path.join(artfolder,'fanart.png'))
    liz.setInfo( type="Video", infoLabels={ "Title": name })
    ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=pasta,totalItems=number_of_items)
    return ok


def is_ascii(s):
    return all(ord(c) < 128 for c in s)


def nowPlaying(channel):
    url = 'http://preview.tvzune.co/program/xprog/'+ channel +'_agora.txt'
    print url
    req = urllib2.Request(url)
    response = urllib2.urlopen(req)
    data = response.read()
    result = unicodedata.normalize('NFKD',unicode(data,'utf-16', errors='ignore')).encode('ascii','ignore')
    print result
    response.close()
    return result.split('\n')[0]

def login():
    url = 'http://tvzune.tv/m/index.php?a=login'
    values = { 'username': _username,'password': _password }
    data = urllib.urlencode(values)
    req = urllib2.Request(url, data)
    req.add_header('Accept-Encoding', 'utf-8')
    response = urllib2.urlopen(req)
    lines = response.readlines()
    result = ''
    for line in lines:
        if is_ascii(line):
            if re.compile(".*\\x00.*").match(line) is None:
                result += line + '\n'
    channels(result)
    xbmcplugin.endOfDirectory(int(sys.argv[1]))

def channels(html):
    files = re.compile("file: '([^,]+?)'").findall(html)
    _file = ""
    for f in files:
        _file = f
    match = re.compile('<img id="(.+?)" class="canais" src="img/(.+?).png"/>').findall(html)
    for name, img in match:
        ch = Channel(url = _file.replace("sporttv1",name), title = name.upper(), icon ='http://tvzune.tv/m/img/'+ img +'.png' )
        ch.nowPlaying = nowPlaying(name)
        print ch.nowPlaying
        _channels.append(ch)
    setup_channels(_channels)


def setup_channels(channels):
    for ch in channels:
        addDir(ch.title + ' - ' + ch.nowPlaying, ch.url, '2', ch.icon, 1, False)
    xbmc.executebuiltin("Container.SetViewMode(51)")


def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]

        return param

try: _mode=int(get_params()["mode"])
except:
	try:
		_mode=get_params()["mode"]
	except: pass

print _mode

if _mode is None:
    login()
elif _mode == 2:
    _url = get_params()["url"]
    _name = get_params()["name"]
    print get_params()
    playListItem(urllib.unquote(_url), _name)
    #playVideo()
#notification()
#playVideo()
#login()
